/*
  线程安排它退出时的清理操作
  1.创建两个线程
  2.线程1、2中分别执行清除操作
  3.pthread_cleanup_pop(0)表示不执行pthread_cleanup_pop(非0)表示执行
  4.如果先执行了pthread_exit(),pthread_cleanup_pop(0)也会响应并清理线程
*/

#include "spu.h"

void clean_handle(void *arg)
{
    printf("clean %s\n",arg);
}

void *thread_fun1(void *arg)
{
    void *__retval;
    printf("I am thread 1\n");
    
    pthread_cleanup_push(clean_handle, "pthread01_1");
	pthread_exit(__retval);
    // 先执行pthread_exit，pthread_cleanup_pop(0)也会响应并清理线程
    pthread_cleanup_pop(0);  //非0即执行操作
}

void *thread_fun2(void *arg)
{
    printf("I am thread 2\n");
    
    pthread_cleanup_push(clean_handle, "pthread02_1"); //先入栈后出
    pthread_cleanup_push(clean_handle, "pthread02_2"); 

    pthread_cleanup_pop(1);   //非0即执行操作
    pthread_cleanup_pop(1);   //非0即执行操作

	return (void*)2;
}

int main(int argc, char *argv[])
{	
	int err1, err2;
	pthread_t thread_id1, thread_id2; 
    int s;

    void *__retval;

	err1 = pthread_create(&thread_id1, NULL, thread_fun1, NULL);
	if(err1 != 0)
		printf("create thread01 failed!\n");

    err2 = pthread_create(&thread_id2, NULL, thread_fun2, NULL);
	if(err2 != 0)
		printf("create thread02 failed!\n"); 

    sleep(2);
    pthread_exit(__retval);
}

